# -*- coding: utf-8 -*-
from . import BaseController
from backend.libs import myjson as json
from backend.models import Tag, Video
from backend.libs import err_result_const as err_const
from datetime import datetime


class TagListController(BaseController):

    def get(self):
        t = Tag.objects
        tag_name = self.get_argument('tagName', '')
        if tag_name:
            t = t.filter(name__contains=tag_name)

        state = self.int_argument('state', 0)
        t = t.filter(state=state).order_by('state', 'show_order')
        
        number_per_page = self.int_argument('pageSize', 100)
        paginator = self.pagination(t.all(), number_per_page=number_per_page)

        return self.render_json(data=paginator)


class DetailController(BaseController):

    def get(self):
        id = self.int_argument('id', -1)
        if id <= 0:
            return self.render_json(code=1001, msg='参数错误')
        tag = Tag.objects.filter(id=id).first()
        if not tag:
            return self.render_json(code=1001, msg='标签不存在')
        return self.render_json(data=tag.to_detail_dict())


class AllTagController(BaseController):

    def get(self):
        data = {
            'tags': [ t.to_dict() for t in Tag.objects.filter(state=0).order_by('show_order').all() ]
        }

        return self.render_json(data=data)


class CreateTagController(BaseController):

    def post(self):
        data = json.loads(self.request.body)
        if not data['name']:
            return self.render_json(code=1001, msg='标签名称不能为空')
        tag_id = data.get('id', -1)

        if int(tag_id) <= 0:
            tag = Tag() 
            tag.create_time = datetime.now()
        else:
            tag = Tag.objects.filter(id=tag_id).first()
        tag.update_time = datetime.now()
        tag.name = data['name']
        tag.state = data['state']
        tag.show_order = data['show_order']
        tag.save()
        return self.render_json(data=tag.to_dict())


class DeleteTagController(BaseController):

    def post(self, tag_id):
        tag_id = int(tag_id)
        if tag_id <= 0:
            return self.render_json(code=err_const.PARAM_ERR['code'], msg=err_const.PARAM_ERR['msg'])
        videos = Video.objects.filter(tags__id=tag_id).all()
        if len(videos) > 0:
            return self.render_json(code=1002, msg='该标签已关联到视频！请先从视频下取消该标签！')
        tag = Tag.objects.filter(id=tag_id).first()
        if tag:
            tag.delete()

        return self.render_json()
